//  WDGroMorePublic.m
//  WDGroMore

#import "WDGroMorePublic.h"
#import "GroMoreSDKManager.h"
#import "WDGroMoreTrackManager.h"
#import "WDInAppPurchaseManager.h"
#import "WDInAppPurchaseHandleManager.h"
#import "WDGroMoreThinkingManager.h"
#import "UMAnalytics.h"
#import "WDGroMoreDelegateManager.h"
#import "WDBMS.h"
#import "UMAnalytics.h"
#import "WDGroMoreBADSignalManager.h"
#import "BMSLifecycleManager.h"
#import "BMSOnlineSessionManager.h"
#import "BMSRealnamePopupView.h"
#import "BMSPopupQueueManager.h"
#import "BMSKeychain.h"
#import "BMSPrivate.h"
#import "BMSAuthManager.h"

@interface WDGroMorePublic ()

@end

@implementation WDGroMorePublic

static WDGroMorePublic *_manager = nil;

+ (instancetype)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

#pragma mark - 广告配置

- (void)GroMoreDelegate:(id)delegate {
    [WDGroMoreDelegateManager manager].delegate = delegate;
}

- (void)initWindMillAdsWithNetworkDetection:(BOOL)detection {
    [GroMoreSDKManager shared].isDebug = self.isDebug;
    [GroMoreSDKManager shared].isUnity = self.isUnity;
}

- (void)showGroMoreRewardVideoAd {
    [[GroMoreSDKManager shared] showRewardVideo];
}

- (void)showGroMoreIntersititialAd {
    [[GroMoreSDKManager shared] showInterstitial];
}

- (void)showGroMoreBannerAdWithTop:(BOOL)top {
    [[GroMoreSDKManager shared] showBannerAtTop:top];
}

- (void)GroMoreCloseBannerAd {
    [[GroMoreSDKManager shared] closeBanner];
}

- (void)GroMoreShowSplashAd {
    [[GroMoreSDKManager shared]showSplashAd];
}

- (void)tryShowSplashAdWithLaunch {
    [[GroMoreSDKManager shared]tryShowSplashAdWithLaunch];
}
- (void)GroMoreShowNativeAd {
    [[GroMoreSDKManager shared]showNativeAd];
}

/// 显示原生广告（支持位置与偏移）
/// @param position 0=底部，1=顶部
/// @param yOffset 相对于顶部或底部的偏移量，按 1334 高度比例缩放
- (void)showNativeAdAtPosition:(NSInteger)position yOffset:(CGFloat)yOffset {
    [[GroMoreSDKManager shared]showNativeAdAtPosition:position yOffset:yOffset];
}

/// 移除原生广告视图
- (void)removeNativeAd {
    [[GroMoreSDKManager shared]removeNativeAd];
}

#pragma mark - 统计

- (void)initAnalyticsSDK {
    [WDGroMoreTrackManager setup];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@(1) forKey:BMS_TRACK_DISABLE_THINKING];
}

- (void)thinkingEventWithKey:(NSString *)key jsonStr:(id)jsonStr {
    [[WDGroMoreThinkingManager manager]thinkingTrackEventWithKey:key jsonStr:jsonStr];
}

- (void)UMEventWithKey:(NSString *)key jsonStr:(id)jsonStr {
    [UMAnalytics umcEvent:key params:jsonStr];
}

#pragma mark - 内购

- (void)WDLaunchInAppPurchase:(NSString *)productId {
    [[WDInAppPurchaseManager shareInAppPurchaseManager] launchInAppPurchase:productId];
}

- (void)WDRestoreInAppPurchase:(NSString *)productId {
    [[WDInAppPurchaseManager shareInAppPurchaseManager] restoreInAppPurchase:productId];
}

- (void)WDRequestProductLists {
    if (self.onProductListCallBack) {
        self.onProductListCallBack([WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds);
    }
}

#pragma mark - 参数配置

- (NSString *)WDGetUUID {
    return [WDGroMorePublic manager].uuid.length !=0  ? [WDGroMorePublic manager].uuid : [BMSKeychain WDKeychainGetUUID];
}

- (void)WDBannerDirectionWithTop:(BOOL)topDir {
    // 已废弃，统一使用 showBannerAdWithTop:
}

- (NSDictionary *)WDGetBMSContent {
    return @{}; // TODO: 支持后端下发参数逻辑
}

#pragma mark ------ BMS ---------

- (void)initSDKCompletion:(BMSInitCompletion)completion {
    [[BMSAuthSDK shareInstance]initSDKCompletion:completion];
}

-(void)showPrivacyPopupWithCompletion:(void (^)(BOOL))completion {
    [[BMSAuthSDK shareInstance]showPrivacyPopupWithCompletion:completion];
}

- (void)showRealnamePopupWithCompletion:(void (^)(BOOL success))completion {
    [[BMSAuthSDK shareInstance]showRealnamePopupWithCompletion:completion];
}

- (void)openTerms {
    [[BMSAuthSDK shareInstance]openTerms];
}

- (void)openPrivacy {
    [[BMSAuthSDK shareInstance]openPrivacy];
}

-(void)openH5WithUrl:(NSString *)url {
    [[BMSAuthSDK shareInstance]openH5WithUrl:url];
}


/// 单次震动，默认样式（短促）
- (void)vibrateOnce {
    [[BMSAuthSDK shareInstance]vibrateOnce];
}

/// 自定义震动（使用 CoreHaptics 模拟间隔+时长震动）
- (void)vibrateWithPattern:(NSArray<NSNumber *> *)pattern
                    repeat:(NSInteger)repeat {
    [[BMSAuthSDK shareInstance]vibrateWithPattern:pattern repeat:repeat];
}

/// 取消震动（如果可取消）
- (void)vibrateCancel {
    [[BMSAuthSDK shareInstance]vibrateCancel];
}

#pragma mark ---- life cycle -------

- (void)WDApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([BMSLifecycleManager isFirstLaunchByInstallDate]) {
        [BMSOpMergeEventBuilder event_userOpWithAct:BMS_EVENT_BASE_INSTALL description:BMS_WDS_FIRST_LAUNCH_AFTER_INSTALL];
        
        [WDGroMoreTrackManager track:BMS_EVENT_BASE_GAME_START params:@{BMS_PARAM_WDS:BMS_WDS_USER_ENTER_GAME,BMS_PARAM_TAB1:@"首次"} dType:BMS_DTYPE_USER_ACTION desc:BMS_WDS_USER_ENTER_GAME options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    }
    
    [WDGroMoreTrackManager track:BMS_EVENT_BASE_GAME_START params:@{BMS_PARAM_WDS:BMS_WDS_USER_ENTER_GAME,BMS_PARAM_TAB1:@"非首次"} dType:BMS_DTYPE_USER_ACTION desc:BMS_WDS_USER_ENTER_GAME options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    
    
    [[WDGroMoreBADSignalManager shareInstance]BADSignalDidFinishLaunchingWithOptions:launchOptions connectOptions:nil];
//    __block BOOL realNameIng = NO;
    [WDGroMorePublic manager].realNameIng = NO;
    BOOL didRealnameAuth = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSKeyRealnameAuth];
    if (!didRealnameAuth) {
        
        [BMSOnlineSessionManager shared].onTickCheck = ^(NSTimeInterval totalSeconds) {
            [WDGroMorePublic manager].shouldShowRealnamePopup = NO;
            
            [[NSUserDefaults standardUserDefaults]setBool:NO forKey:kBMSShouldShowRealnamePopup];
            
            [BMSInitializer shared].hasShownForcedRealnamePopup = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSForcedRealname];
            BOOL shouldShowRealnamePopup = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSShouldShowRealnamePopup];
            if (totalSeconds >= 3600 &&
                !shouldShowRealnamePopup &&
                [BMSInitializer shared].hasShownForcedRealnamePopup) {
                
                BOOL _didRealNameAuth = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSKeyRealnameAuth];
                if(!_didRealNameAuth && ![WDGroMorePublic manager].realNameIng) {
                    [WDGroMorePublic manager].shouldShowRealnamePopup = YES;
                    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:kBMSShouldShowRealnamePopup];
                    [WDGroMorePublic manager].realNameIng = YES;
                    [BMSInitializer shared].hasShownForcedRealnamePopup = YES;
                    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:kBMSForcedRealname];
                    
                    // 需要实名弹窗
                    [[BMSOnlineSessionManager shared]stopTracking];
                    BMSAuthManager *manager = [[BMSAuthManager alloc] init];
                    [manager showRealnamePopupWithCompletion:^(BOOL success) {
                        [WDGroMorePublic manager].realNameIng = NO;
                    }];
                }else {
                    [[BMSOnlineSessionManager shared]stopTracking];
                }
            }
        };
    }else {
        [[BMSOnlineSessionManager shared]stopTracking];
    }
}

- (void)WDApplicationWillEnterForeground:(UIApplication *)application {
    [[BMSOnlineSessionManager shared]appWillEnterForeground];
}

- (void)WDApplicationDidEnterBackground:(UIApplication *)application {
    [[BMSOnlineSessionManager shared]appDidEnterBackground];
}

- (void)WDApplication:(UIApplication *)application
              openURL:(NSURL *)url
              options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    [[WDGroMoreBADSignalManager shareInstance]BADSignalAnylyseDeeplinkClickidWithOpenUrl:url];
}



@end
